package by.DmitrenkoKovalev.DeenDonBell;

import java.util.Random;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;

public class BroadCastRecieverCallListener extends BroadcastReceiver {
	static Ringtone ringtone;
	public static Context mContext;
	private static Random random = new Random();
	Context context;
	DBFiles dbHelper;

	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		if (mContext == null)
			mContext = arg0;
		TelephonyManager TelMan = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);

		if (TelMan.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
			RingtoneManager.setActualDefaultRingtoneUri(
					BroadCastRecieverCallListener.mContext,
					RingtoneManager.TYPE_RINGTONE, Uri.EMPTY);
			dbHelper = new DBFiles(BroadCastRecieverCallListener.mContext);
			if (!(dbHelper.getFromDB().isEmpty())) {
				Uri ringtoneUri = Uri.parse(dbHelper.getFromDB().get(
						random.nextInt(dbHelper.getFromDB().size())));
				Log.d("MyLog", ringtoneUri.toString());

				if ((ringtone == null) || (ringtoneUri == null)) {
					ringtone = RingtoneManager
							.getRingtone(
									BroadCastRecieverCallListener.mContext,
									ringtoneUri);
					Log.d("MyLog", "ringtone is null");
					ringtone.play();
				} else {
					Log.d("MyLog", "ringtone is detected");
				}
			}
		}
		if (TelMan.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
			Log.d("MyLog", "ofhook");
			if (!(ringtone == null)) {
				ringtone.stop();
				ringtone = null;
			}
		}
		if (TelMan.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
			Log.d("MyLog", "idle");
			if (!(ringtone == null)) {
				ringtone.stop();
				ringtone = null;
			}
		}
	}
}
